/* Alastair Smith 8/31/2021: RevisedJuly 2022
Analysis of instability for a paper. Use new measure of W.  

Replication Materials for Institutional Change as a Response to Unrealized Threats: An Empirical Analysis: Bruce Bueno de Mesquita and Alaastair Smith: Forthcoming Journal of Conflict Resolution. 

MAIN DATA SOURCES 
"National Political Leaders and Causes of Death", https://doi.org/10.7910/DVN/U1MYGI,
sick=1 implies leader will die within 5 years from a chronic Cause
eAge = leader Age- Swedish life expectancy
LC = leader change during year

A New Indicator of Coalition Size: Tests Against Standard Regime-Type Indicators. Smith, Alastair M., 2022, "Replication Data for: A New Indicator of Coalition Size: Tests Against Standard Regime-Type Indicators", https://doi.org/10.7910/DVN/UYLXRO,
W4 = coalition size

Events data from BANK CNTS 
gen logRiots=log(Riots+1);gen logStrikes=log(Strikes+1);gen logRevolutions=log(Revolutions+1);
gen logDemo=log(AntiGovDem+1);gen logPopBanks =log(pop1);
gen revyn=0; replace revyn=1 if Revolutions>0; replace revyn=. if Revolutions==.;
 gen coupsyn=0; replace coupsyn=1 if NumberofCoupsdEtat>0; replace coupsyn=. if NumberofCoupsdEtat==.;
/* Measure of Protest*/ 
egen sRiot=std(logRiots) ;egen sStrikes=std(logStrikes);egen sDemo=std(logDemo);
gen Prot = (sDemo+sStrikes+sRiot)/3; drop  sDemo sStrikes sRiot;
label var Prot "Meaure of Masses actions against the government: from Banks CNTS, riots Anti-gove Demo and Strikes";
/* rescale protest to have a min value of zero */ 
sum Prot; replace Prot=(Prot-r(min)); 
gen LProt=L.Prot; 
capture gen PurgeYN=0 if Purges~=.;capture replace PurgeYN=1 if Purges~=. & Purges>0;


/* COUP data: downloaded 2/11/2018 from http://www.systemicpeace.org/inscrdata.html
 "data/constituentdata/coup/coup", */ 
 gen Coup = scoup1+ atcoup2+ pcoup3; /* sum of successful, unsuccesful attempt and official plot allegations */ 
gen AnyCoup =(Coup>0);replace AnyCoup=. if Coup==.; gen coupPT=coup1 +coup2+ coup3+ coup4 ; label var AnyCoup "CPS coup data: any coup: suucessful, attempted, planed alledged"; 


/* Coup data from Powell and Thyne: http://www.jonathanmpowell.com/coup-detat-dataset.html 
 Downloaded on 2/11/2020 from http://www.uky.edu/~clthyn2/coup_data/powell_thyne_ccode_year.txt" "data/constituentdata/coup/coupPT"*/ 
 /* Powell and Thyme Coup data 0=no attempt, 1=attempt and 2=success*/ 
gen coupSuccessPT= (coup1==2|coup2==2|coup3==2|coup4==2);
gen AnyCoupPT=(coupPT>0); replace AnyCoupPT=. if coupPT==. ; capture gen AnyCoup12 =(scoup1>0| atcoup2>0); /* successful, unsuccesful attempt but exclude official plot allegations */ 
replace AnyCoup12=. if scoup1==.|atcoup==.; capture gen SucCoup =(scoup1>0); /* successful coup */  replace SucCoup=. if scoup1==.;

NAVCO Data: NAVCO =1 implies the occurrence of protest in Navco data. Defect=1 implies defection by government or security forces

Economic and demographics from World Banks WDI
******************/

#delimit;
/**** Specify path to find data files ****/
capture cd "~/Dropbox/BdMSmithInstability";
/**** Specify where output to be written to ****/ 
global store "InstabilityPaperJuly2022/Replication/writeupinstability/tables";
global pathway "InstabilityPaperJuly2022/Replication";
pwd; 

/**** Specify styles for graphs etc.  ****/
global cs "plot1opts(lcolor(black) lpattern(solid) mcolor(black) msymbol(Oh) lwidth(thick)) plot2opts(lcolor(red)  lpattern(dash) mcolor(red) msymbol(Dh)) ci2opts(lpattern(dash) lcolor(red))";
quietly do "${pathway}/makeLabels.do"; /* list of labels for variables in tables*/ 



use "${pathway}/NationYearNewWdata_March_2022.dta", clear; 

/* Analayis of the NAVCO revolution/protest */ 
sort ccode year; merge 1:1 ccode year using "data/constituentdata/NAVCO/navco_work.dta"; 
drop if _m==2; drop _m; sort ccode year; duplicates report ccode year; 
replace NAVCO=0  if year>1944 & year<=2006 &NAVCO ==.  ; 
replace success=0  if year>1944 & year<=2006 &success ==. ;
replace camp_size=. if camp_size==-99;
replace camp_size=0  if year>1944 & year<=2006 &camp_size==. ;
replace state_defect =. if state_defect ==-99;
replace state_defect =0  if year>1944 & year<=2006 &state_defect ==. ;
replace sec_defect =. if sec_defect ==-99;
replace sec_defect =0  if year>1944 & year<=2006 &sec_defect ==. ;
capture gen DEFECT=max(state_defect,sec_defect);
drop location success progress camp_goals camp_size camp_size_est repression ; 



/**** Extra stata programs needed *******/
/*ssc install carryforward; 
ssc install regen; 
ssc install mplotoffset ;
 ssc install combomarginsplot; */



global vartokeep "country_name year ccode ID leader wiki_x Cause eAge NumberLeaders IncomingTenure LC CountryCode wbcode Purges Riots Revolutions AntiGovDem WeightedConflictIndex RegType NumberofCoupsdEtat ResRents growthWB lifeExp OilRents popWB lgdppc lpop W4 polity2 demaut";

global vartokeep2 "AnyCoupPT Suffrage SICK5y revyn LProt logIncomingTenure PurgeYN NAVCO DEFECT state_defect sec_defect Assassinations Strikes GuerrillaWarfare GovernmentCrises "; 

keep $vartokeep $vartokeep2;

save ${pathway}/InstabilityPaperJCR_Replication.dta , replace;


use ${pathway}/InstabilityPaperJCR_Replication.dta , clear;


label var W4 "W, Winning Coalition Size";
regen  LW=L.W4 ,replace; 
regen  LW2=(L.W4)^2 ,replace; 
regen  LW3=(L.W4)^3 ,replace; 
regen  Ldemaut=L.demaut ,replace; 
regen  Ldemaut2=(L.demaut)^2 ,replace; 
regen  Ldemaut3=(L.demaut)^3 ,replace;
regen Llgdppc=L.lgdppc,replace; 
regen Llpop=L.lpop,replace; 
gen yr=year-1970; gen yr2=yr^2;
gen yr3=yr^3;

/**********************************************************/
/* Political Threats: Revolution, Coup, Defection, Health */ 
/**********************************************************/

/******* Predict revolution and other events *******/
  #delimit;
 regen sick=SICK5y,replace;
    global basicmodel1 "c.LW##c.LW LProt c.LW#c.LProt c.LW#c.LW#c.LProt 
	sick c.LW#c.sick c.LW#c.LW#c.sick 
	logIncomingTenure c.LW#c.logIncomingTenure c.LW#c.LW#c.logIncomingTenure
 eAge  Llgdppc Llpop c.growthWB c.LW#c.growthWB yr* "; 
   global basicmodelDemaut "c.Ldemaut##c.Ldemaut LProt c.Ldemaut#c.LProt c.Ldemaut#c.Ldemaut#c.LProt 
	sick c.Ldemaut#c.sick c.Ldemaut#c.Ldemaut#c.sick 
	logIncomingTenure c.Ldemaut#c.logIncomingTenure c.Ldemaut#c.Ldemaut#c.logIncomingTenure
 eAge  Llgdppc Llpop c.growthWB c.Ldemaut#c.growthWB yr* ";
 global varlist logIncomingTenure sick LProt  ;

 /* REvolution */ 
 xtreg revyn $basicmodel1, fe i(ccode); eststo rev1; 
  estadd scalar turnW = -_b[c.LW]/(2* _b[c.LW#c.LW]);
 estadd scalar turnProt = -_b[c.LW#c.LProt]/(2* _b[c.LW#c.LW#c.LProt]);
  estadd scalar turnTen = -_b[c.LW#c.logIncomingTenure]/(2* _b[c.LW#c.LW#c.logIncomingTenure]);
   estadd scalar turnSICK = -_b[c.LW#c.sick]/(2* _b[c.LW#c.LW#c.sick]);
 capture drop hatrev*;  predict hatrevW, xbu; 
 
 
 /* Margins plot of revolution */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevRev";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of Revolution)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of Revolution)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of Revolution)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Revolution) ;
graph export  "${store}/${n1}.pdf", replace; 
 

   #delimit; /* COUP PT*/
 xtreg AnyCoupPT $basicmodel1, fe i(ccode); eststo coup1;  estadd scalar turnW = -_b[c.LW]/(2* _b[c.LW#c.LW]);
 estadd scalar turnProt = -_b[c.LW#c.LProt]/(2* _b[c.LW#c.LW#c.LProt]);
  estadd scalar turnTen = -_b[c.LW#c.logIncomingTenure]/(2* _b[c.LW#c.LW#c.logIncomingTenure]);
   estadd scalar turnSICK = -_b[c.LW#c.sick]/(2* _b[c.LW#c.LW#c.sick]);
 capture drop hatcoup*;  predict hatcoupW, xbu; 

  
/* Margins plot of Coup */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevCoup";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of Coup)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of Coup)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of Coup)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Coup) ;
graph export  "${store}/${n1}.pdf", replace; 
#delimit;
graph combine  PrevRev PrevCoup,  name(PredRevCoup,replace ) col(1) title("The Revolution and Coup Threats") ;
graph export  "${store}/PredRevCoup.pdf", replace; 

  
 graph combine  PrevRevProtest PrevRevSick PrevRevTenure PrevCoupProtest PrevCoupSick PrevCoupTenure, name(temp,replace ) col(3) ;
 
 
  
  #delimit; /*LEADER CHANGE */
 xtreg LC $basicmodel1, fe i(ccode); eststo lc1;  estadd scalar turnW = -_b[c.LW]/(2* _b[c.LW#c.LW]);
 estadd scalar turnProt = -_b[c.LW#c.LProt]/(2* _b[c.LW#c.LW#c.LProt]);
  estadd scalar turnTen = -_b[c.LW#c.logIncomingTenure]/(2* _b[c.LW#c.LW#c.logIncomingTenure]);
   estadd scalar turnSICK = -_b[c.LW#c.sick]/(2* _b[c.LW#c.LW#c.sick]); 
   capture drop hatLC*;  predict hatLCW, xbu; 

 /* MArgins plot of Leader Change */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevLC";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/; 
  #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Leader Change) ;
graph export  "${store}/${n1}.pdf", replace;
 
 #delimit;
graph combine PrevLC PrevRev PrevCoup,  name(PredictedLCRevCoup,replace ) col(1) title("Threats to Leaders")  ysize(7) xsize(5);
graph export  "${store}/PredictedLCRevCoup.pdf", replace; 
 

 global Ttitle "How Protest, Health and Tenure Affect the Risk of Leader Change, Revolution and Coup";
#delimit;
esttab lc1 rev1 coup1  using "${store}/threatsWextra.tex",replace ar2 r2 se 
   title("$Ttitle (Fixed effects regression analyses) \label{tab:threatsWextra}" ) 
   stats( N N_g r2 r2_w r2_b r2_o turnW turnProt  turnSICK turnTen,
	labels("Observations" "groups" "r2" "within" "btw" "overall" "TurnW" "TurnProt" "TurnSick" "TurnTen")fmt(0 0 %8.4f %8.4f %8.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop(  _cons yr yr2 yr3 ) mlabels("Leader Change" "Revolution" "Coup") substitute(\~ $)   ; 
 
 
#delimit;
esttab lc1 rev1 coup1 using "${store}/threatWxtreg.tex",replace ar2 r2 se 
   title("$Ttitle (Fixed effects regression analyses) \label{tab:threatWxtreg}" ) 
   stats( N N_g r2 ,
	labels("Observations" "Nations" "R2" )fmt(0 0 %8.4f %8.4f %8.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop(  _cons yr yr2 yr3 ) mlabels("Leader Change" "Revolution" "Coup") substitute(\~ $)   ;  
 
 

 
 #delimit; 
 
/**** Events: Fixed effect logit models *****/
xtlogit revyn $basicmodel1, fe i(ccode) ; eststo revL;
 capture drop hatrevlogit*;  predict hatrevlogitpru, pc1;  regen hatrevlogit = log(hatrevlogitpru/(1-hatrevlogitpru)),replace; 
xtlogit AnyCoupPT $basicmodel1, fe i(ccode) ; eststo coupL;
 capture drop hatcouplogit*;  predict hatcouplogitpru, pc1;  regen hatcouplogit = log(hatcouplogitpru/(1-hatcouplogitpru)),replace; 
   
 xtlogit LC $basicmodel1, fe i(ccode) ; eststo LCL;
 capture drop hatLClogit*;  predict hatLClogitpru, pc1;  regen hatLClogit = log(hatLClogitpru/(1-hatLClogitpru)),replace;  
esttab LCL revL   coupL   using "${store}/threats1xtlogit.tex",replace ar2 r2 se 
   title("$Ttitle (FElogit) \label{tab:threats1xtlogit}" ) 
   stats( N N_g /*r2 r2_w r2_b r2_o turnW turnProt  turnSICK turnTen*/,
	labels("Observations" "Nations" )fmt(0 0 %8.4f %8.4f %8.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop(   yr yr2 yr3 ) mlabels("Leader Change" "Revolution" "Coup") substitute(\~ $)   ; 
 
 /* MArgins plot of Leader Change */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevLCxtlogit";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/; 
  #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Leader Change) ;
 

/* estimate using logit and manualy put in FE */
/**** Events: Fixed effect logit models *****/
#delimit ;
logit revyn $basicmodel1 i.ccode ; eststo revynLogit; 
 capture drop hatrevlogit2;  predict hatrevlogit2, xb; 
quietly tabulate ccode if e(sample)==1; 
estadd scalar n_g = r(r); lroc, nograph; estadd scalar lroc= r(area);

 
/* Margins plot of revolution */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevRevLogit";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of Revolution)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of Revolution)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of Revolution)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Revolution) ;
graph export  "${store}/${n1}.pdf", replace;  
 
 
 
 #delimit;
logit AnyCoupPT $basicmodel1 i.ccode;  eststo coupLogit;
 capture drop hatcouplogit2;  predict hatcouplogit2, xb;  
 quietly tabulate ccode if e(sample)==1; 
estadd scalar n_g = r(r); lroc, nograph; estadd scalar lroc= r(area);
  
 
/* Margins plot of Coup */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevCoupLogit";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of Coup)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of Coup)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of Coup)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Coup) ;
graph export  "${store}/${n1}.pdf", replace;  
 
 
  #delimit ;
logit LC $basicmodel1 i.ccode ; eststo LCLogit;
 capture drop hatLClogit2;  predict hatLClogit2, xb;
 quietly tabulate ccode if e(sample)==1; 
estadd scalar n_g = r(r); lroc, nograph; estadd scalar lroc= r(area);
/* MArgins plot of Leader Change */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevLClogit";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/; 
  #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Leader Change) ; 
 
graph combine  PrevLClogit  PrevRevLogit PrevCoupLogit ,col(1) title("Threats to Leaders")  ysize(7) xsize(5);
graph export  "${store}/RiskLogit.pdf", replace;  


#delimit;
esttab LCLogit revynLogit coupLogit using "${store}/threatLogit.tex",replace ar2 r2 se 
   title("$Ttitle (Logit analyses with country fixed effects) \label{tab:threatLogit}" ) 
   stats( N n_g lroc ,
	labels("Observations" "Nations" "ROC" )fmt(0 0 %8.4f %8.4f %8.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop(  _cons yr yr2 yr3 *.ccode ) mlabels("Leader Change" "Revolution" "Coup") substitute(\~ $)   ;  
 

 
 #delimit;
/**** Events: Fixed effect Reg using Polity  *****/
xtreg revyn $basicmodelDemaut, fe i(ccode) ; eststo revDemaut;
 capture drop hatrevDemaut;  predict hatrevDemaut, xbu;  
 
/* Margins plot of revolution */ 
 #delimit; 
 quietly margins, at(Ldemaut=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevRevDemaut";
 #delimit;
  mplotoffset, xdimension(Ldemaut) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of Revolution)  
  xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(Ldemaut=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(Ldemaut) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of Revolution)  
  xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(Ldemaut=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(Ldemaut) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of Revolution)  
  xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Revolution) ;
graph export  "${store}/${n1}.pdf", replace;  
 
  
  #delimit;
 
xtreg AnyCoupPT $basicmodelDemaut, fe i(ccode) ; eststo coupDemaut;
 capture drop hatcoupDemaut;  predict hatcoupDemaut ,xbu; 
 
/* Margins plot of Coup */ 
 
 quietly margins, at(Ldemaut=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevCoupDemaut";
 #delimit;
  mplotoffset, xdimension(Ldemaut) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of Coup)  
  xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "NoProtest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(Ldemaut=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(Ldemaut) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of Coup)  
  xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(Ldemaut=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(Ldemaut) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of Coup)  
  xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Coup) ;
graph export  "${store}/${n1}.pdf", replace; 
#delimit;
graph combine  PrevRevDemaut PrevCoupDemaut,  name(PredRevCoupDemaut,replace ) col(1) title("The Revolution and Coup Threats") ;
graph export  "${store}/PredRevCoupDemaut.pdf", replace; 

  
 graph combine  PrevRevProtest PrevRevSick PrevRevTenure PrevCoupProtest PrevCoupSick PrevCoupTenure, name(temp,replace ) col(3) ; 
 
 
 
 
 
   #delimit;
 xtreg LC $basicmodelDemaut, fe i(ccode) ; eststo LCDemaut;
 capture drop hatLCD;  predict hatLCDemaut,xbu;  
 
 /* MArgins plot of Leader Change */ 
 #delimit; 
 quietly margins, at(Ldemaut=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevLCdemaut";
 #delimit;
  mplotoffset, xdimension(Ldemaut) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of LC)  
  xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(Ldemaut=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(Ldemaut) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of LC)  
  xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(Ldemaut=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(Ldemaut) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of LC)  
  xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/; 
  #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Leader Change) ;
graph export  "${store}/${n1}.pdf", replace;
 
 #delimit;
graph combine PrevLCdemaut PrevRevDemaut PrevCoupDemaut,  name(PredictedLCRevCoupDemaut,replace ) col(1) title("Threats to Leaders")  ysize(7) xsize(5);
graph export  "${store}/PredictedLCRevCoupDemaut.pdf", replace;  
 
 
esttab LCDemaut revDemaut   coupDemaut   using "${store}/threatsDemautxtreg.tex",replace ar2 r2 se 
   title("$Ttitle (Fixed effect regression analyses with Polity as the institutional measure) \label{tab:threatsDemautxtreg}" ) 
   stats( N N_g r2 /*r2_w r2_b r2_o turnW turnProt  turnSICK turnTen*/ ,
	labels("Observations" "Nations" "r2" "within" "btw" "overall" "TurnW" "TurnProt" "TurnSick" "TurnTen")fmt(0 0 %8.4f %8.4f %8.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 ) mlabels("Leader Change" "Revolution" "Coup") substitute(\~ $)   ;  
 
 
 save "bookproject/December2020/NewWpaper/temp_crap.dta",replace;  
 */
#delimit; 
 use "bookproject/December2020/NewWpaper/temp_crap.dta" , clear;
 
 /************* ****************************************** *********/
 /************* Change in Institutions of the Next 2 years *********/
  /************* ****************************************** *********/
 #delimit;
 regen D2W= F2.W4 - L.W4,replace ;  regen F2W= F2.W4,replace ;  
 /*global modelbasicWevents "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatrev  c.hatcoup c.rev AnyCoupPT  yr* i.ccode";
global modelbasicWb "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatLC LC c.hatrev revyn c.hatcoup  AnyCoupPT yr* i.ccode";
global modelbasicWc "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatLC LC c.hatrev revyn c.hatcoup  AnyCoupPT yr* i.ccode";
global modelbasicWc_control "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatLC LC c.hatrev revyn c.hatcoup  AnyCoupPT growthWB c.LW#c.growthWB c.LW##c.Llgdppc Llpop yr* i.ccode";
*/
 global title "How the Occurrence of Leader Change, Revolution and Coup and the Risk of these Events Affects the Direction and Volatility of Institutional Change";
global modelfullW3 "c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.hatLC c.LW#c.hatLC  LC c.LW#c.LC c.hatrev  c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global modelbasicW3 "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatLC c.hatrev  c.hatcoup   yr* i.ccode";
global modelbasicWevents3 "c.LW c.LW#c.LW  c.LW#c.LW#c.LW LC c.rev AnyCoupPT  yr* i.ccode";
global modelbasicWboth3 "c.LW c.LW#c.LW  c.LW#c.LW#c.LW LC c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode";


global modelfullW "c.LW c.LW#c.LW   c.hatLC c.LW#c.hatLC  LC c.LW#c.LC c.hatrev  c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global modelbasicW "c.LW c.LW#c.LW   c.hatLC c.hatrev  c.hatcoup   yr* i.ccode";
global modelbasicWevents "c.LW c.LW#c.LW   LC c.rev AnyCoupPT  yr* i.ccode";
global modelbasicWboth "c.LW c.LW#c.LW   LC c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode";

global sigmaWfull "c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.hatLC LC c.LW#LC c.hatrev  c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop ";  
global sigmaWsmall3 "c.hatLC LC  c.LW c.LW#c.LW  c.LW#c.LW#c.LW   ";
global sigmaWsmall "c.hatLC LC  c.LW c.LW#c.LW     ";  
 global sigmaWrevcoup "c.hatLC LC  c.LW#c.hatLC c.LW#c.LC c.LW c.LW#c.LW  c.LW#c.LW#c.LW   "; 
  #delimit;
  
/** Program to calc stat for tables **/ 
capture program drop addstuff; program define addstuff; estadd scalar fe feNation;  estadd scalar AIC = 2 *e(k)-2*e(ll);capture drop hatfull; predict hatfull if sam==1, xb; regen resfull2=(D2W-hatfull)^2 if sam==1,replace; sum resfull2 if sam==1; scalar resfullSum = r(sum);
estadd scalar r2non= (resNonSum-resfullSum)/resNonSum;end;   
  
/**** Use xtreg predictions ****/ 
regen hatrev = hatrevW,replace; regen hatcoup=hatcoupW,replace ; regen hatLC=hatLCW,replace; 
  #delimit; /*** run a regression to find common sample **/ 
hetregress D2W $modelbasicWboth , het($sigmaWsmall ); regen sam=e(sample),replace;
/* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);

hetregress D2W $modelbasicWevents, het($sigmaWsmall ); eststo m0; 
addstuff;

hetregress D2W $modelbasicW, het($sigmaWsmall ); eststo m1;addstuff;
hetregress D2W $modelbasicWboth, het($sigmaWsmall ); eststo m2;addstuff;
hetregress D2W c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==0& F.LC==0, het(c.hatLC    c.LW c.LW#c.LW  c.LW#c.LW#c.LW    ); regen sam=e(sample),replace; 
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);
hetregress D2W c.LW c.LW#c.LW    c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==0& F.LC==0, het(c.hatLC    c.LW c.LW#c.LW      );
eststo m3; addstuff; 

#delimit;
hetregress D2W c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==1| F.LC==1, het(c.hatLC   c.LW c.LW#c.LW     ); regen sam=e(sample),replace; 
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);
hetregress D2W c.LW c.LW#c.LW    c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==1| F.LC==1, het(c.hatLC   c.LW c.LW#c.LW      );
eststo m4;addstuff; 
global DWtitle "How Leader Change, Revolution, Coup and the Threat of these Events Affect Institutional Change and Institutional Volatility"; 
global mtitle " "Events" "Risk" "Both" "No LC" "LC" "; 
    #delimit;
 esttab m0 m1 m2   using "${store}/SimpleD2W.tex",replace ar2 r2 se 
   title("$DWtitle (Risks estimated from analyses in table \ref{tab:threatWxtreg})  \label{tab:SimpleD2W}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels( "Events" "Risk" "Both" "No LC" "LC" ) substitute(\~ $)   ;  

 esttab m0 m1 m2 m3 m4  using "${store}/SimpleD2WExtra.tex",replace ar2 r2 se 
   title("$DWtitle (Risks estimated from analyses in table \ref{tab:threatWxtreg})  \label{tab:SimpleD2WExtra}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.2f %11.2f %11.2f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels($mtitle ) substitute(\~ $)   ;  
 
/* Graph of distribution of W for the sample being used here */ 
 /***** Distribution of W in the sample and in the whole data set ******/
 twoway (kdensity W4 ,lcolor(black) lwidth(thick)) (kdensity W4 if sam==1,lcolor(red) lwidth(thick) lpattern(dash)), ytitle("Density") title("Distribution of Winning Coalition Size") subtitle("All Observations (solid); Observations In Analyses (dash)" ) xtitle("W, Winning Coalition Size") name(kdensityW,replace) legend(col(1) order(1 "Full Sample" 2  "Sample In Analyses"));
 graph export "${store}/kdensityW.pdf",replace;
#delimit;
twoway (kdensity W4 if sam==1 ,lcolor(black) lwidth(thick))  (fpfit revyn W4 if sam==1 &W4>.125, lcolor(red) lwidth(thick) lpattern(dash_dot) yaxis(2)) (fpfit AnyCoup W4 if sam==1 & W4>.125, yaxis(2) lcolor(blue) lwidth(thick) lpattern(dash)) , legend(order(1 "Distribution of W" 2 "Revolution" 3 "Coup" ))  ytitle("Prevalence of Revolution and Coup", axis(2)) ytitle("Density of W" ) title("Distribution of W and the Likelihood of Revolutions and Coup") xtitle("W, Winning Coalition Size") name(EventsGraph ,replace);
graph export "${store}/EventsGraph.pdf",replace;
  

/*  Examination of Purge data */
#delimit; /*** run a regression to find common sample **/ 
hetregress PurgeYN $modelbasicWboth , het($sigmaWsmall ); regen sam=e(sample),replace;
/* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress PurgeYN if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(PurgeYN-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);

hetregress PurgeYN $modelbasicWevents, het($sigmaWsmall ); eststo m0; 
addstuff;

hetregress PurgeYN $modelbasicW, het($sigmaWsmall ); eststo m1;addstuff;
hetregress PurgeYN $modelbasicWboth, het($sigmaWsmall ); eststo m2;addstuff;
hetregress PurgeYN c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==0& F.LC==0, het(c.hatLC    c.LW c.LW#c.LW  c.LW#c.LW#c.LW    ); regen sam=e(sample),replace; 
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress PurgeYN if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);
hetregress PurgeYN c.LW c.LW#c.LW    c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==0& F.LC==0, het(c.hatLC    c.LW c.LW#c.LW      );
eststo m3; addstuff; 

#delimit;
hetregress PurgeYN c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==1| F.LC==1, het(c.hatLC   c.LW c.LW#c.LW     ); regen sam=e(sample),replace; 
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress PurgeYN if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(PurgeYN-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);
hetregress PurgeYN c.LW c.LW#c.LW    c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==1| F.LC==1, het(c.hatLC   c.LW c.LW#c.LW      );
eststo m4;addstuff; 
global title "Determinants of Purges"; 
global mtitle " "Events" "Risk" "Both" "No LC" "LC" "; 
    #delimit;
 esttab m0 m1 m2   using "${store}/SimplePurge.tex",replace ar2 r2 se 
   title("$title \label{tab:SimplePurge}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels( "Events" "Risk" "Both" "No LC" "LC" ) substitute(\~ $)   ;  

 esttab m0 m1 m2 m3 m4  using "${store}/SimplePurgeExtra.tex",replace ar2 r2 se 
   title("$title \label{tab:SimplePurgeExtra}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels($mtitle ) substitute(\~ $)   ;  
 


 
/**** Use xtreg predictions: Nation Specific Cubic Spline ****/ 
#delimit;
regen hatrev = hatrevW,replace; regen hatcoup=hatcoupW,replace ; regen hatLC=hatLCW,replace; 
/* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);
  

hetregress D2W $modelbasicWevents  growthWB c.LW#c.growthWB Llgdppc Llpop i.ccode#c.yr i.ccode#c.yr2 i.ccode#c.yr3, het($sigmaWsmall ); eststo m0; 
hetregress D2W $modelbasicW growthWB c.LW#c.growthWB Llgdppc Llpop i.ccode#c.yr i.ccode#c.yr2 i.ccode#c.yr3, het($sigmaWsmall ); eststo m1;
hetregress D2W $modelbasicWboth growthWB c.LW#c.growthWB Llgdppc Llpop i.ccode#c.yr i.ccode#c.yr2 i.ccode#c.yr3, het($sigmaWsmall ); eststo m2;
#delimit;
 esttab m0 m1 m2  using "${store}/NSCS.tex",replace ar2 r2 se 
   title("$title (With Nation-Specific Time Trends) \label{tab:threatsDemaut}" ) 
   stats( N ll r2  ,
	labels("Observations" "ll" "r2" )fmt(0  %10.4f %8.4f %8.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode#c.yr3 *.ccode#c.yr2 *.ccode#c.yr *.ccode) mlabels($mtitle ) substitute(\~ $)   ; 
 
 
 #delimit;
/***** Linear Interactions *******/ 
global linearInteractEvents "c.LW c.LW#c.LW      LC c.LW#c.LC revyn c.LW#c.revyn AnyCoupPT c.LW#c.AnyCoupPT growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global linearInteractRisks "c.LW c.LW#c.LW   c.hatLC c.LW#c.hatLC c.hatrev  c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global linearInteractBoth "c.LW c.LW#c.LW      LC c.LW#c.LC  revyn c.LW#c.revyn AnyCoupPT c.LW#c.AnyCoupPT c.hatLC c.LW#c.hatLC c.hatrev  c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";


hetregress D2W $linearInteractBoth, het($sigmaWsmall ); regen sam=e(sample),replace; /* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);

hetregress D2W $linearInteractEvents if sam==1  , het($sigmaWsmall ); eststo m0; addstuff;
hetregress D2W $linearInteractRisks if sam==1 , het($sigmaWsmall ); eststo m1;addstuff;
hetregress D2W $linearInteractBoth if sam==1 , het($sigmaWsmall ); eststo m2; addstuff;
#delimit;
esttab m0 m1 m2  using "${store}/linearInteract.tex",replace ar2 r2 se 
   title(" $title \label{tab:linearInteract}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels( $mtitle ) substitute(\~ $)   ;  
 
#delimit;
/***** Quadratic Interactions *******/ 
global quadInteractEvents "c.LW c.LW#c.LW       LC c.LW#c.LC c.LW#c.LW#c.LC revyn c.LW#c.revyn c.LW#c.LW#c.revyn AnyCoupPT c.LW#c.AnyCoupPT c.LW#c.LW#c.AnyCoupPT growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global quadInteractRisks "c.LW c.LW#c.LW    c.hatLC c.LW#c.hatLC c.LW#c.LW#c.hatLC c.hatrev  c.LW#c.hatrev c.LW#c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup c.LW#c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global quadInteractBoth "c.LW c.LW#c.LW       LC c.LW#c.LC c.LW#c.LW#c.LC revyn c.LW#c.revyn c.LW#c.LW#c.revyn AnyCoupPT c.LW#c.AnyCoupPT c.LW#c.LW#c.AnyCoupPT c.hatLC c.LW#c.hatLC c.LW#c.LW#c.hatLC c.hatrev  c.LW#c.hatrev c.LW#c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup c.LW#c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";


global sigmaWquadinteract "LC c.LW#c.LC c.LW#c.LW#c.LC c.hatLC c.LW#c.hatLC c.LW#c.LW#c.hatLC  c.LW c.LW#c.LW ";  

hetregress D2W $quadInteractBoth, het($sigmaWquadinteract ); regen sam=e(sample),replace; /* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);

hetregress D2W $quadInteractEvents if sam==1 , het($sigmaWquadinteract ); eststo m0; addstuff;
hetregress D2W $quadInteractRisks if sam==1 , het($sigmaWquadinteract ); eststo m1;addstuff;
#delimit; 
hetregress D2W $quadInteractBoth if sam==1 , het($sigmaWquadinteract); eststo m2; addstuff;
#delimit;
esttab m0 m1 m2  using "${store}/quadInteract.tex",replace ar2 r2 se 
   title(" $DWtitle (The risks are estimates from the fixed effects regression analyses show in table \ref{tab:threatWxtreg})\label{tab:quadInteract}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.2f %11.2f %11.2f %8.2f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels( $mtitle ) substitute(\~ $)   ;  
 
/***** +Create Margins Plot for the Quadratic interaction ******/  
quiet sum hatrev,detail; global hatrevL = r(p10); global hatrevH = r(p90); 
quiet sum hatcoup,detail; global hatcoupL = r(p10); global hatcoupH = r(p90);
 quiet sum hatLC,detail; global hatLCL = r(p10); global hatLCH = r(p90);
 /* Rev Risk: Directional change */ 
 #delimit;
quietly margins, at(LW=(.1(.1)1) hatrev=($hatrevL,$hatrevH) hatcoup=($hatcoupL) hatLC=$hatLCL

LC=0 AnyCoupPT=0 revyn=0 ) vsquish  ; 
 #delimit; 
 global n1 marginDw2; 
  mplotoffset, xdimension(LW) plotdimension(at(hatrev) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatrev , replace)  ylabel(-.2(.1).2) $cs   title(Revolutionary Risk)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;
  /* Coup Risk: Directional change */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) 
hatrev=($hatrevL ) hatcoup=($hatcoupL,$hatcoupH) hatLC=($hatLCL )
LC=0 AnyCoupPT=0 revyn=0) vsquish  ;  

  mplotoffset, xdimension(LW) plotdimension(at(hatcoup) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatcoup , replace) ylabel(-.2(.1).2)  $cs   title(Coup Risk)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}hatrev ${n1}hatcoup , col(3) title("How Political Risks Influence Institutions") name(${n1}Risks,replace);  
  
/* Actual Events: Directional change */ 
 #delimit;
quietly margins, at(LW=(.1(.1)1) hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL )
LC=0 AnyCoupPT=0 revyn=(0,1) ) vsquish  ; 
 #delimit; 
 global n1 marginDw2; 
  mplotoffset, xdimension(LW) plotdimension(at(revyn) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}rev , replace) ylabel(-.2(.1).2)  $cs   title(Revolution)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Revolution" 2  "Revolution")) cap() /*note("hello")*/;
  /* Coup: Directional change */ 
#delimit;
quietly margins, at(LW=(.1(.1)1)
hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL )
LC=0 AnyCoupPT=(0,1) revyn=0) vsquish  ;  

  mplotoffset, xdimension(LW) plotdimension(at(AnyCoupPT) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}coup , replace) ylabel(-.2(.1).2)  $cs   title(Coup)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Coup" 2  "Coup")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}rev ${n1}coup , col(3) title("How Political Events Influence Institutions") name(${n1}Events,replace); 

#delimit;
graph combine   ${n1}Events ${n1}Risks , col(1) title("How Political Events and Risks Influence Institutions") name(${n1}EventsRisk,replace); 
graph export ${store}/${n1}EventsRisk.pdf,replace;


  /* Actual LC: volatility */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) 
hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL )

LC=(0,1) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace);
 mplotoffset, xdimension(LW) plotdimension(at(LC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolLC , replace)   $cs ylabel(-12(2)-2)  title(Leader Change)    ytitle(Volatility in W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) cap() /*note("hello")*/;  
preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolLCs2 , replace) title(Leader Change)    ytitle("Volatility in W, {&sigma}{sup:2}" ) ylabel(0(.01).06)   xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) ;  


 /* Risk LC: volatility */ 
#delimit;
quietly margins, at(LW=(.1(.1)1)
hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL,$hatLCH) 
LC=(0) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace); 
 mplotoffset, xdimension(LW) plotdimension(at(hatLC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolhatLC , replace)   $cs ylabel(-12(2)-2)  title(Leader Change Risk)    ytitle(Volatility in W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;
 
preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolhatLCs2 , replace) title(Leader Change Risk)    ytitle("Volatility in W, {&sigma}{sup:2}" ) ylabel(0(.01).06)   xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) ;  
 
  #delimit;  
 
graph combine ${n1}VolLC ${n1}VolhatLC, col(3) name(${n1}VolEventsRisks, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/${n1}VolEventsRisks.pdf",replace; 
 graph combine ${n1}VolLCs2 ${n1}VolhatLCs2, col(3) name(${n1}VolEventsRiskss2, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/${n1}VolEventsRiskss2.pdf",replace;
  
  

 
 
 #delimit;
 /******* With Demaut ********/
 global modelfullD "c.Ldemaut c.Ldemaut#c.Ldemaut    c.hatLC c.Ldemaut#c.hatLC  LC c.Ldemaut#c.LC c.hatrev  c.Ldemaut#c.hatrev c.hatcoup c.Ldemaut#c.hatcoup growthWB c.Ldemaut#c.growthWB Llgdppc Llpop yr* i.ccode";
global modelbasicD "c.Ldemaut c.Ldemaut#c.Ldemaut   c.hatLC c.hatrev  c.hatcoup   yr* i.ccode";
global modelbasicDevents "c.Ldemaut c.Ldemaut#c.Ldemaut   LC c.rev AnyCoupPT  yr* i.ccode";
global modelbasicDboth "c.Ldemaut c.Ldemaut#c.Ldemaut   LC c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode";

global sigmaDfull "c.Ldemaut c.Ldemaut#c.Ldemaut  c.Ldemaut#c.Ldemaut#c.Ldemaut  c.hatLC LC c.Ldemaut#LC c.hatrev  c.Ldemaut#c.hatrev c.hatcoup c.Ldemaut#c.hatcoup growthWB c.Ldemaut#c.growthWB Llgdppc Llpop ";  
global sigmaDsmall "c.hatLC LC  c.Ldemaut c.Ldemaut#c.Ldemaut     "; 
 global sigmaDrevcoup "c.hatLC LC  c.Ldemaut#c.hatLC c.Ldemaut#c.LC c.Ldemaut c.Ldemaut#c.Ldemaut  c.Ldemaut#c.Ldemaut#c.Ldemaut   "; 
 /**** Use xtreg demaut predictions ****/ 
regen hatrev = hatrevDemaut,replace; regen hatcoup=hatcoupDemaut,replace ; regen hatLC=hatLCDemaut,replace;
  
   #delimit;
hetregress D2W $modelbasicDevents, het($sigmaDsmall ); eststo m0; 
hetregress D2W $modelbasicD, het($sigmaDsmall ); eststo m1;
hetregress D2W $modelbasicDboth, het($sigmaDsmall ); eststo m2; regen sam=e(sample), replace; 
    #delimit;
 esttab m0 m1 m2  using "${store}/tempDemaut.tex",replace ar2 r2 se 
   title("$DWtitle (Polity measure of Institutions \label{tab:threatsDemaut}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels() substitute(\~ $)   ;  
  
 
/* Graph of distribution of W for the sample being used here */ 
 /***** Distribution of W in the sample and in the whole data set ******/
 twoway (kdensity demaut ,lcolor(black) lwidth(thick) bwidth(.2)) (kdensity demaut if sam==1,lcolor(red) lwidth(thick) lpattern(dash) bwidth(.2)), ytitle("Density") title("Distribution of Polity") subtitle("All Observations (solid); Observations In Analyses (dash)" ) xtitle("Polity") name(kdensityDemaut,replace) legend(col(1) order(1 "Full Sample" 2  "Sample In Analyses"));
 graph export "${store}/kdensityDemaut.pdf",replace;
#delimit;
twoway (kdensity demaut if sam==1 , bwidth(.2)lcolor(black) lwidth(thick))  (fpfit revyn demaut if sam==1 , lcolor(red) lwidth(thick) lpattern(dash_dot) yaxis(2)) (fpfit AnyCoup demaut if sam==1 ,ylabel(0(.2)1) yaxis(2) lcolor(blue) lwidth(thick) lpattern(dash)) , legend(order(1 "Distribution of Polity" 2 "Revolution" 3 "Coup" ))  ytitle("Prevalence of Revolution and Coup", axis(2)) ytitle("Density of Polity" ) title("Distribution of Polity and the Likelihood of Revolutions and Coup") xtitle("Polity") name(EventsGraphDemaut ,replace);
graph export "${store}/EventsGraphDemaut.pdf",replace;
  
 
 
 
#delimit;
/***** DEMAUT: Quadratic Interactions *******/ 
global quadInteractEventsD "c.Ldemaut c.Ldemaut#c.Ldemaut       LC c.Ldemaut#c.LC c.Ldemaut#c.Ldemaut#c.LC revyn c.Ldemaut#c.revyn c.Ldemaut#c.Ldemaut#c.revyn AnyCoupPT c.Ldemaut#c.AnyCoupPT c.Ldemaut#c.Ldemaut#c.AnyCoupPT growthWB c.Ldemaut#c.growthWB Llgdppc Llpop yr* i.ccode";
global quadInteractRisksD "c.Ldemaut c.Ldemaut#c.Ldemaut    c.hatLC c.Ldemaut#c.hatLC c.Ldemaut#c.Ldemaut#c.hatLC c.hatrev  c.Ldemaut#c.hatrev c.Ldemaut#c.Ldemaut#c.hatrev c.hatcoup c.Ldemaut#c.hatcoup c.Ldemaut#c.Ldemaut#c.hatcoup growthWB c.Ldemaut#c.growthWB Llgdppc Llpop yr* i.ccode";
global quadInteractBothD "c.Ldemaut c.Ldemaut#c.Ldemaut       LC c.Ldemaut#c.LC c.Ldemaut#c.Ldemaut#c.LC revyn c.Ldemaut#c.revyn c.Ldemaut#c.Ldemaut#c.revyn AnyCoupPT c.Ldemaut#c.AnyCoupPT c.Ldemaut#c.Ldemaut#c.AnyCoupPT c.hatLC c.Ldemaut#c.hatLC c.Ldemaut#c.Ldemaut#c.hatLC c.hatrev  c.Ldemaut#c.hatrev c.Ldemaut#c.Ldemaut#c.hatrev c.hatcoup c.Ldemaut#c.hatcoup c.Ldemaut#c.Ldemaut#c.hatcoup growthWB c.Ldemaut#c.growthWB Llgdppc Llpop yr* i.ccode";

global sigmaDquadinteract "LC c.Ldemaut#c.LC c.Ldemaut#c.Ldemaut#c.LC c.hatLC c.Ldemaut#c.hatLC c.Ldemaut#c.Ldemaut#c.hatLC  c.Ldemaut c.Ldemaut#c.Ldemaut "; 


regen hatrev = hatrevDemaut,replace; regen hatcoup=hatcoupDemaut,replace ; regen hatLC=hatLCDemaut,replace;

#delimit;
hetregress D2W $quadInteractBothD, het($sigmaDquadinteract); regen sam=e(sample),replace; /* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);

hetregress D2W $quadInteractEventsD if sam==1 , het($sigmaDquadinteract ); eststo m0; addstuff;
hetregress D2W $quadInteractRisksD if sam==1 , het($sigmaDquadinteract ); eststo m1;addstuff;
hetregress D2W $quadInteractBothD if sam==1 , het($sigmaDquadinteract ); eststo m2; addstuff;
#delimit;
esttab m0 m1 m2  using "${store}/quadInteractDemaut.tex",replace ar2 r2 se 
   title(" $DWtitle (Polity is used as the measure of institutions. The risks are obtained from the fixed effects regression results reported in table \ref{tab:threatsDemautxtreg}) \label{tab:quadInteractDemaut}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels( $mtitle ) substitute(\~ $)   ;  
 
/***** +Create Margins Plot for the Quadratic interaction ******/   
quiet sum hatrev,detail; global hatrevL = r(p10); global hatrevH = r(p90); 
quiet sum hatcoup,detail; global hatcoupL = r(p10); global hatcoupH = r(p90);
 quiet sum hatLC,detail; global hatLCL = r(p10); global hatLCH = r(p90);
 /* Rev Risk: Directional change */ 
 #delimit;
quietly margins, at(Ldemaut=(.1(.1)1) 
hatrev=($hatrevL,$hatrevH) hatcoup=($hatcoupL ) hatLC=($hatLCL )
LC=0 AnyCoupPT=0 revyn=0 ) vsquish  ; 
 #delimit; 
 global n1 marginDw2Demaut; 
  mplotoffset, xdimension(Ldemaut) plotdimension(at(hatrev) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatrev , replace) ylabel(-.3(.1).3)  $cs   title(Revolutionary Risk)    ytitle({&Delta}Polity)    xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;
  /* Coup Risk: Directional change */ 
#delimit;
quietly margins, at(Ldemaut=(.1(.1)1) 
hatrev=($hatrevL ) hatcoup=($hatcoupL,$hatcoupH) hatLC=($hatLCL ) 
LC=0 AnyCoupPT=0 revyn=0) vsquish  ;  

  mplotoffset, xdimension(Ldemaut) plotdimension(at(hatcoup) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatcoup , replace)   $cs ylabel(-.3(.1).3)  title(Coup Risk)    ytitle({&Delta}Polity)    xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}hatrev ${n1}hatcoup , col(3) title("How Political Risks Influence Institutions") name(${n1}Risks,replace);  
  
/* Actual Events: Directional change */ 
 #delimit;
quietly margins, at(Ldemaut=(.1(.1)1) hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL )
LC=0 AnyCoupPT=0 revyn=(0,1) ) vsquish  ; 
 #delimit; 
 global n1 marginDw2Demaut; 
  mplotoffset, xdimension(Ldemaut) plotdimension(at(revyn) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}rev , replace)   $cs ylabel(-.3(.1).3)  title(Revolution)    ytitle({&Delta}Polity)    xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Revolution" 2  "Revolution")) cap() /*note("hello")*/;
  /* Coup: Directional change */ 
#delimit;
quietly margins, at(Ldemaut=(.1(.1)1) 
hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL )
LC=0 AnyCoupPT=(0,1) revyn=0) vsquish  ;  

  mplotoffset, xdimension(Ldemaut) plotdimension(at(AnyCoupPT) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}coup , replace)   $cs ylabel(-.3(.1).3)  title(Coup)    ytitle({&Delta}Polity)    xtitle(Polity{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Coup" 2  "Coup")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}rev ${n1}coup , col(3) title("How Political Events Influence Institutions") name(${n1}Events,replace); 

#delimit;
graph combine   ${n1}Events ${n1}Risks , col(1) title("How Political Events and Risks Influence Institutions") name(${n1}EventsRisk,replace); 
graph export ${store}/${n1}EventsRisk.pdf,replace;

 
  /* Actual LC: volatility */ 
#delimit;
quietly margins, at(Ldemaut=(.1(.1)1) 
hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL )
LC=(0,1) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace); 
 mplotoffset, xdimension(Ldemaut) plotdimension(at(LC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolLC , replace)   $cs ylabel(-10(2)0)  title(Leader Change)    ytitle(Volatility in Polity)    xtitle(Polity{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) cap() /*note("hello")*/;  
  #delimit; 

preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolLCs2 , replace) title(Leader Change)    ytitle("Volatility in Polity, {&sigma}{sup:2}" ) ylabel(0(.02).1)   xtitle(Polity{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) ;   
  
   
 /* Risk LC: volatility */ 
#delimit;
quietly margins, at(Ldemaut=(.1(.1)1) hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL,$hatLCH)
LC=(0) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace); ; 
 mplotoffset, xdimension(Ldemaut) plotdimension(at(hatLC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolhatLC , replace)   $cs ylabel(-10(2)0)   title(Leader Change Risk)    ytitle(Volatility in Polity)    xtitle(Polity{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;  
  #delimit;  
 preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolhatLCs2 , replace) title(Leader Change Risk)    ytitle("Volatility in Polity, {&sigma}{sup:2}" ) ylabel(0(.02).1)   xtitle(Polity{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) ;   
  
 
graph combine ${n1}VolLC ${n1}VolhatLC, col(3) name(${n1}VolEventsRisks, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/${n1}VolEventsRisks.pdf",replace; 
  
 graph combine ${n1}VolLCs2 ${n1}VolhatLCs2, col(3) name(${n1}VolEventsRiskss2, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/${n1}VolEventsRiskss2.pdf",replace;  


 
 
 
 
 
 
 
  /**** Use logit w FE predictions ****/ 
  #delimit;
regen hatrev = hatrevlogit2,replace; regen hatcoup=hatcouplogit2,replace ; regen hatLC=hatLClogit2,replace;

quiet sum hatrev,detail; global hatrevL = r(p10); global hatrevH = r(p90); 
quiet sum hatcoup,detail; global hatcoupL = r(p10); global hatcoupH = r(p90);
 quiet sum hatLC,detail; global hatLCL = r(p10); global hatLCH = r(p90);


   #delimit;
 /* Quadratic specifications with xtlogit risks */ 
hetregress D2W $quadInteractBoth, het($sigmaWquadinteract ); regen sam=e(sample),replace; /* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);

hetregress D2W $quadInteractEvents if sam==1 , het($sigmaWquadinteract ); eststo m0; addstuff;
hetregress D2W $quadInteractRisks if sam==1 , het($sigmaWquadinteract ); eststo m1;addstuff;
#delimit; 
hetregress D2W $quadInteractBoth if sam==1 , het($sigmaWquadinteract); eststo m2; addstuff;
#delimit;
global title "How the Occurrence of Leader Change, Revolution and Coup and the Risk of these Events Affects the Direction and Volatility of Institutional Change"; 
esttab m0 m1 m2  using "${store}/quadInteractXtLogit.tex",replace ar2 r2 se 
   title(" $DWtitle (Risk estimated from logit specification with nation fixed effects in table~\ref{tab:threatLogit}) \label{tab:quadInteractXtLogit}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels( $mtitle ) substitute(\~ $)   ;  
 
 /****** Margins Plot using the logit with fixed effects as the measure of risk ****/ 
 /***** +Create Margins Plot for the Quadratic interaction ******/   
 /* Rev Risk: Directional change */ 
 #delimit;
quietly margins, at(LW=(.1(.1)1) hatrev=($hatrevL,$hatrevH) hatcoup=($hatcoupL) hatLC=$hatLCL
LC=0 AnyCoupPT=0 revyn=0 ) vsquish  ;
 #delimit; 

 global n1 marginDw2Logit; 
  mplotoffset, xdimension(LW) plotdimension(at(hatrev) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatrev , replace)  ylabel(-.3(.1).3) $cs   title(Revolutionary Risk)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;
  /* Coup Risk: Directional change */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) hatcoup=($hatcoupL,$hatcoupH) hatrev=($hatrevL) hatLC=$hatLCL
LC=0 AnyCoupPT=0 revyn=0) vsquish  ;  

  mplotoffset, xdimension(LW) plotdimension(at(hatcoup) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatcoup , replace) ylabel(-.3(.1).3)  $cs   title(Coup Risk)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}hatrev ${n1}hatcoup , col(3) title("How Political Risks Influence Institutions") name(${n1}Risks,replace);  
  
/* Actual Events: Directional change */ 
 #delimit;
quietly margins, at(LW=(.1(.1)1) hatrev=($hatrevL) hatcoup=($hatcoupL) hatLC=$hatLCL
LC=0 AnyCoupPT=0 revyn=(0,1) ) vsquish  ; 
 #delimit; 
 
  mplotoffset, xdimension(LW) plotdimension(at(revyn) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}rev , replace) ylabel(-.3(.1).3)  $cs   title(Revolution)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Revolution" 2  "Revolution")) cap() /*note("hello")*/;
  /* Coup: Directional change */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) hatcoup=($hatcoupL) hatrev=($hatrevL) hatLC=$hatLCL
LC=0 AnyCoupPT=(0,1) revyn=0) vsquish  ;  

  mplotoffset, xdimension(LW) plotdimension(at(AnyCoupPT) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}coup , replace) ylabel(-.3(.1).3)  $cs   title(Coup)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Coup" 2  "Coup")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}rev ${n1}coup , col(3) title("How Political Events Influence Institutions") name(${n1}Events,replace); 

#delimit;
graph combine   ${n1}Events ${n1}Risks , col(1) title("How Political Events and Risks Influence Institutions") name(${n1}EventsRisk,replace); 
graph export ${store}/${n1}EventsRisk.pdf,replace;

 
  /* Actual LC: volatility */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) hatcoup=($hatcoupL) hatrev=($hatrevL) hatLC=($hatLCL)
LC=(0,1) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace);
 mplotoffset, xdimension(LW) plotdimension(at(LC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolLC , replace)   $cs ylabel(-12(2)-2)  title(Leader Change)    ytitle(Volatility in W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) cap() /*note("hello")*/;  
preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolLCs2 , replace) title(Leader Change)    ytitle("Volatility in W, {&sigma}{sup:2}" ) ylabel(0(.02).1)   xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) ;  


 /* Risk LC: volatility */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) hatcoup=(0) hatrev=(0) hatLC=(-.3,1)
LC=(0) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace); 
 mplotoffset, xdimension(LW) plotdimension(at(hatLC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolhatLC , replace)   $cs ylabel(-12(2)-2)  title(Leader Change Risk)    ytitle(Volatility in W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;
 
preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolhatLCs2 , replace) title(Leader Change Risk)    ytitle("Volatility in W, {&sigma}{sup:2}" ) ylabel(0(.02).1)   xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) ;  
 
  #delimit;  
 
graph combine ${n1}VolLC ${n1}VolhatLC, col(3) name(${n1}VolEventsRisks, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/VolEventsRisks.pdf",replace; 
 graph combine ${n1}VolLCs2 ${n1}VolhatLCs2, col(3) name(${n1}VolEventsRiskss2, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/${n1}VolEventsRiskss2.pdf",replace;
  


  
  
/***** Very bsic logit without fixed effects ********/ 
/* estimate using basic logit without FE */

#delimit ;
logit revyn $basicmodel1  ; eststo revynbasicL; 
 capture drop hatrevbasicL;  predict hatrevbasicL, xb; 
quietly tabulate ccode if e(sample)==1; 
estadd scalar n_g = r(r); lroc, nograph; estadd scalar lroc= r(area);

 
/* Margins plot of revolution */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevRevbasicL";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of Revolution)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of Revolution)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of Revolution)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Revolution) ;
graph export  "${store}/${n1}.pdf", replace;  
 
 
 
 #delimit;
logit AnyCoupPT $basicmodel1 ;  eststo coupbasicL;
 capture drop hatcoupbasicL;  predict hatcoupbasicL, xb;  
 quietly tabulate ccode if e(sample)==1; 
estadd scalar n_g = r(r); lroc, nograph; estadd scalar lroc= r(area);
  
 
/* Margins plot of Coup */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevCoupbasicL";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of Coup)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of Coup)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of Coup)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Coup) ;
graph export  "${store}/${n1}.pdf", replace;  
 
 
  #delimit ;
logit LC $basicmodel1 ; eststo LCbasicL;
 capture drop hatLCbasicL;  predict hatLCbasicL, xb;
 quietly tabulate ccode if e(sample)==1; 
estadd scalar n_g = r(r); lroc, nograph; estadd scalar lroc= r(area);
/* MArgins plot of Leader Change */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevLCbasicL";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of LC)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/; 
  #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Leader Change) ; 
 
graph combine  PrevLCbasicL  PrevRevbasicL PrevCoupbasicL ,col(1) title("Threats to Leaders")  ysize(7) xsize(5);
graph export  "${store}/RiskbasicL.pdf", replace;  


#delimit;
esttab LCbasicL revynbasicL coupbasicL using "${store}/threatbasicL.tex",replace ar2 r2 se 
   title("$Ttitle (Logit analyses without fixed effects) \label{tab:threatbasicL}" ) 
   stats( N n_g lroc ,
	labels("Observations" "Nations" "ROC" )fmt(0 0 %8.4f %8.4f %8.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop(  _cons yr yr2 yr3  ) mlabels("Leader Change" "Revolution" "Coup") substitute(\~ $)   ; 
 
 
 
 
 
  /**** Use logit without FE predictions ****/ 
  #delimit;
regen hatrev = hatrevbasicL,replace; regen hatcoup=hatcoupbasicL,replace ; regen hatLC=hatLCbasicL,replace;
regen D2W=F2.W4-L.W4,replace;

   #delimit;
 /* Quadratic specifications with basic logit risks */ 
hetregress D2W $quadInteractBoth, het($sigmaWquadinteract ); regen sam=e(sample),replace; /* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);

hetregress D2W $quadInteractEvents if sam==1 , het($sigmaWquadinteract ); eststo m0; addstuff;
hetregress D2W $quadInteractRisks if sam==1 , het($sigmaWquadinteract ); eststo m1;addstuff;
#delimit; 
hetregress D2W $quadInteractBoth if sam==1 , het($sigmaWquadinteract); eststo m2; addstuff;
#delimit;
global title "How the Occurrence of Leader Change, Revolution and Coup and the Risk of these Events Affects the Direction and Volatility of Institutional Change"; 
esttab m0 m1 m2  using "${store}/D2WbasicL.tex",replace ar2 r2 se 
   title(" $title (Risks estimated from logit specification in table \ref{tab:threatbasicL}) \label{tab:D2WbasicL}")
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels( $mtitle ) substitute(\~ $)   ;  
 
 /****** Margins Plot using the logit with fixed effects as the measure of risk ****/ 
 quiet sum hatrev,detail; global hatrevL = r(p10); global hatrevH = r(p90); 
quiet sum hatcoup,detail; global hatcoupL = r(p10); global hatcoupH = r(p90);
 quiet sum hatLC,detail; global hatLCL = r(p10); global hatLCH = r(p90);
 /***** +Create Margins Plot for the Quadratic interaction ******/   
 /* Rev Risk: Directional change */ 
 #delimit;
quietly margins, at(LW=(.1(.1)1) hatrev=($hatrevL,$hatrevH) hatcoup=($hatcoupL) hatLC=$hatLCL
LC=0 AnyCoupPT=0 revyn=0 ) vsquish  ; 
 #delimit; 
 global n1 marginDw2basicL; 
  mplotoffset, xdimension(LW) plotdimension(at(hatrev) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatrev , replace)  ylabel(-.3(.1).3) $cs   title(Revolutionary Risk)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;
  /* Coup Risk: Directional change */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) hatcoup=($hatcoupL,$hatcoupH ) hatrev=($hatrevL) hatLC=$hatLCL
LC=0 AnyCoupPT=0 revyn=0) vsquish  ;  

  mplotoffset, xdimension(LW) plotdimension(at(hatcoup) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatcoup , replace) ylabel(-.3(.1).3)  $cs   title(Coup Risk)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}hatrev ${n1}hatcoup , col(3) title("How Political Risks Influence Institutions") name(${n1}Risks,replace);  
  
/* Actual Events: Directional change */ 
 #delimit;
quietly margins, at(LW=(.1(.1)1) hatrev=($hatrevL) hatcoup=($hatcoupL) hatLC=$hatLCL
LC=0 AnyCoupPT=0 revyn=(0,1) ) vsquish  ; 
 #delimit; 
 
  mplotoffset, xdimension(LW) plotdimension(at(revyn) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}rev , replace) ylabel(-.3(.1).3)  $cs   title(Revolution)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Revolution" 2  "Revolution")) cap() /*note("hello")*/;
  /* Coup: Directional change */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) hatrev=($hatrevL) hatcoup=($hatcoupL) hatLC=$hatLCL
LC=0 AnyCoupPT=(0,1) revyn=0) vsquish  ;  

  mplotoffset, xdimension(LW) plotdimension(at(AnyCoupPT) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}coup , replace) ylabel(-.3(.1).3)  $cs   title(Coup)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Coup" 2  "Coup")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}rev ${n1}coup , col(3) title("How Political Events Influence Institutions") name(${n1}Events,replace); 

#delimit;
graph combine   ${n1}Events ${n1}Risks , col(1) title("How Political Events and Risks Influence Institutions") name(${n1}EventsRisk,replace); 
graph export ${store}/${n1}EventsRisk.pdf,replace;

 
  /* Actual LC: volatility */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) hatcoup=($hatcoupL) hatrev=($hatrevL) hatLC=($hatLCL)
LC=(0,1) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace);
 mplotoffset, xdimension(LW) plotdimension(at(LC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolLC , replace)   $cs ylabel(-12(2)-2)  title(Leader Change)    ytitle(Volatility in W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) cap() /*note("hello")*/;  
preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolLCs2 , replace) title(Leader Change)    ytitle("Volatility in W, {&sigma}{sup:2}" ) ylabel(0(.02).1)   xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) ;  


 /* Risk LC: volatility */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) hatcoup=($hatcoupL) hatrev=($hatrevL) hatLC=($hatLCL,$hatLCH)
LC=(0) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace); 
 mplotoffset, xdimension(LW) plotdimension(at(hatLC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolhatLC , replace)   $cs ylabel(-12(2)-2)  title(Leader Change Risk)    ytitle(Volatility in W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;
 
preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolhatLCs2 , replace) title(Leader Change Risk)    ytitle("Volatility in W, {&sigma}{sup:2}" ) ylabel(0(.02).1)   xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) ;  
 
  #delimit;  
 
graph combine ${n1}VolLC ${n1}VolhatLC, col(3) name(${n1}VolEventsRisks, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/VolEventsRisks.pdf",replace; 
 graph combine ${n1}VolLCs2 ${n1}VolhatLCs2, col(3) name(${n1}VolEventsRiskss2, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/${n1}VolEventsRiskss2.pdf",replace;
 
 
 
/********* ROBUSTNESS use NAVCO measure instead of revolution **********/


/**** For Robustness lets look at the occurrence of NAVCO events ***/
 /* NAVCO */ 
 #delimit;
 xtreg NAVCO $basicmodel1, fe i(ccode); eststo nav1;
  estadd scalar turnW = -_b[c.LW]/(2* _b[c.LW#c.LW]);
 estadd scalar turnProt = -_b[c.LW#c.LProt]/(2* _b[c.LW#c.LW#c.LProt]);
  estadd scalar turnTen = -_b[c.LW#c.logIncomingTenure]/(2* _b[c.LW#c.LW#c.logIncomingTenure]);
   estadd scalar turnSICK = -_b[c.LW#c.sick]/(2* _b[c.LW#c.LW#c.sick]);
 capture drop hatNAVCO*;  predict hatNAVCOW, xbu; 
  global Ttitle "How Protest, Health and Tenure Affect the Risk of a Protest Campaign Against the Government (NAVCO)";
  
  
#delimit;
esttab nav1 using "${store}/PrevNAVCO.tex",replace ar2 r2 se 
   title("$Ttitle (Fixed effects regression analyses) \label{tab:PrevNAVCO}" ) 
   stats( N N_g r2 ,
	labels("Observations" "Nations" "R2" )fmt(0 0 %8.4f %8.4f %8.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop(  _cons yr yr2 yr3 ) mlabels("NAVCO Campaign") substitute(\~ $)   ;  
   
  
 
 
 /* Margins plot of NAVCO */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevNAVCO";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of NAVCO)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend( col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of NAVCO)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend( col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of NAVCO)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend( col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(NAVCO Protest Movement) ;
graph export  "${store}/${n1}.pdf", replace; 
 

 /**** For Robustness lets look at the occurrence of DEFECTION by coalition to support a protest movement  ***/
 /* NAVCO  DEFECT */ 
 #delimit;
 xtreg DEFECT $basicmodel1, fe i(ccode); eststo nav1;
  estadd scalar turnW = -_b[c.LW]/(2* _b[c.LW#c.LW]);
 estadd scalar turnProt = -_b[c.LW#c.LProt]/(2* _b[c.LW#c.LW#c.LProt]);
  estadd scalar turnTen = -_b[c.LW#c.logIncomingTenure]/(2* _b[c.LW#c.LW#c.logIncomingTenure]);
   estadd scalar turnSICK = -_b[c.LW#c.sick]/(2* _b[c.LW#c.LW#c.sick]);
 capture drop hatDEFECT*;  predict hatDEFECT, xbu; 
 
 
 /* Margins plot of NAVCO DEFECT */ 
 #delimit; 
 quietly margins, at(LW=(.1(.1)1) LProt=(0, 1.291) ) vsquish;
 global n1 "PrevDEFECT";
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(LProt) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Protest , replace)   $cs  
 title(Protest)
   ytitle(Likelihood of Defection)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "No Protest" 2  "High Protest")) cap() /*note("hello")*/;
 
 quietly margins, at(LW=(.1(.1)1) logIncomingTenure=(0,3) ) vsquish;
 #delimit;
  mplotoffset, xdimension(LW) plotdimension(at(logIncomingTenure) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Tenure , replace)   $cs  
 title(Leader Tenure)
   ytitle(Likelihood of Defection)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "New Leader" 2  "Long Tenure")) cap() /*note("hello")*/;
 #delimit;
 quietly margins, at(LW=(.1(.1)1) sick=(0,1) ) vsquish;
 
  mplotoffset, xdimension(LW) plotdimension(at(sick) , labels("HE" "sick") 
  )  byopts(title(""))  
  name(${n1}Sick , replace)   $cs  
 title(Leader Health)
   ytitle(Likelihood of Defection)  
  xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(off col(1) order(1 "Healthy" 2  "Sick")) cap() /*note("hello")*/;
 #delimit;
graph combine  ${n1}Protest ${n1}Sick ${n1}Tenure, name(${n1},replace ) col(3) title(Coalition Defection to Support a NAVCO Protest Movement) ;
graph export  "${store}/${n1}.pdf", replace; 


/********************** Institutional Change and NAVCO as measure of revolution ***/
#delimit;
regen hatrev = hatNAVCOW,replace; regen hatcoup=hatcoupW,replace ; regen hatLC=hatLCW,replace;



hetregress D2W $modelbasicWboth, het($sigmaWsmall ); eststo mSimple;addstuff;

#delimit;
/***** Quadratic Interactions *******/ 
global quadInteractEvents "c.LW c.LW#c.LW       LC c.LW#c.LC c.LW#c.LW#c.LC revyn c.LW#c.revyn c.LW#c.LW#c.revyn AnyCoupPT c.LW#c.AnyCoupPT c.LW#c.LW#c.AnyCoupPT growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global quadInteractRisks "c.LW c.LW#c.LW    c.hatLC c.LW#c.hatLC c.LW#c.LW#c.hatLC c.hatrev  c.LW#c.hatrev c.LW#c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup c.LW#c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global quadInteractBoth "c.LW c.LW#c.LW       LC c.LW#c.LC c.LW#c.LW#c.LC revyn c.LW#c.revyn c.LW#c.LW#c.revyn AnyCoupPT c.LW#c.AnyCoupPT c.LW#c.LW#c.AnyCoupPT c.hatLC c.LW#c.hatLC c.LW#c.LW#c.hatLC c.hatrev  c.LW#c.hatrev c.LW#c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup c.LW#c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";


global sigmaWquadinteract "LC c.LW#c.LC c.LW#c.LW#c.LC c.hatLC c.LW#c.hatLC c.LW#c.LW#c.hatLC  c.LW c.LW#c.LW ";  

hetregress D2W $quadInteractBoth, het($sigmaWquadinteract ); regen sam=e(sample),replace; /* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);

hetregress D2W $quadInteractEvents if sam==1 , het($sigmaWquadinteract ); eststo m0; addstuff;
hetregress D2W $quadInteractRisks if sam==1 , het($sigmaWquadinteract ); eststo m1;addstuff;
#delimit; 
hetregress D2W $quadInteractBoth if sam==1 , het($sigmaWquadinteract); eststo m2; addstuff;
#delimit;
esttab mSimple m0 m1 m2  using "${store}/quadInteractNAVCO.tex",replace ar2 r2 se 
   title(" $DWtitle (Revolutions and revolution risk is measured using the NAVCO project's definition of Campaigns. The revolutionary risks are estimates from the fixed effects regression analyses show in table \ref{tab:PrevNAVCO})\label{tab:quadInteractNAVCO}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels( "Both" "Events" "Risks" "Both") substitute(\~ $)   ;  
 
 
 
 
/***** +Create Margins Plot for the Quadratic interaction ******/  
quiet sum hatrev,detail; global hatrevL = r(p10); global hatrevH = r(p90); 
quiet sum hatcoup,detail; global hatcoupL = r(p10); global hatcoupH = r(p90);
 quiet sum hatLC,detail; global hatLCL = r(p10); global hatLCH = r(p90);
 /* Rev Risk: Directional change */ 
 #delimit;
quietly margins, at(LW=(.1(.1)1) hatrev=($hatrevL,$hatrevH) hatcoup=($hatcoupL) hatLC=$hatLCL

LC=0 AnyCoupPT=0 revyn=0 ) vsquish  ; 
 #delimit; 
 global n1 NAVCODw2; 
  mplotoffset, xdimension(LW) plotdimension(at(hatrev) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatrev , replace)  ylabel(-.2(.1).2) $cs   title(Risk of NAVCO Campaign)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;
  /* Coup Risk: Directional change */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) 
hatrev=($hatrevL ) hatcoup=($hatcoupL,$hatcoupH) hatLC=($hatLCL )
LC=0 AnyCoupPT=0 revyn=0) vsquish  ;  

  mplotoffset, xdimension(LW) plotdimension(at(hatcoup) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}hatcoup , replace) ylabel(-.2(.1).2)  $cs   title(Coup Risk)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}hatrev ${n1}hatcoup , col(3) title("How Political Risks Influence Institutions") name(${n1}Risks,replace);  
  
/* Actual Events: Directional change */ 
 #delimit;
quietly margins, at(LW=(.1(.1)1) hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL )
LC=0 AnyCoupPT=0 revyn=(0,1) ) vsquish  ; 
 #delimit; 
 global n1 NAVCODw2; 
  mplotoffset, xdimension(LW) plotdimension(at(revyn) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}rev , replace) ylabel(-.2(.1).2)  $cs   title(NAVCO Campaign)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Campaign" 2  "NAVCO Campaign")) cap() /*note("hello")*/;
  /* Coup: Directional change */ 
#delimit;
quietly margins, at(LW=(.1(.1)1)
hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL )
LC=0 AnyCoupPT=(0,1) revyn=0) vsquish  ;  

  mplotoffset, xdimension(LW) plotdimension(at(AnyCoupPT) , labels("HE" "sick") 
  )  byopts(title(""))      name(${n1}coup , replace) ylabel(-.2(.1).2)  $cs   title(Coup)    ytitle({&Delta}W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)
  legend(col(1) order(1 "No Coup" 2  "Coup")) cap() /*note("hello")*/;

  #delimit;
graph combine   ${n1}rev ${n1}coup , col(3) title("How Political Events Influence Institutions") name(${n1}Events,replace); 

#delimit;
graph combine   ${n1}Events ${n1}Risks , col(1) title("How Political Events and Risks Influence Institutions") name(${n1}EventsRisk,replace); 
graph export ${store}/${n1}EventsRisk.pdf,replace;
#delimit;
graph combine   ${n1}rev ${n1}hatrev , col(3) title("Occurrence and Risk of NAVCO Campaigns and Change in W") name(${n1}Events,replace); 
graph export ${store}/${n1}EventsRisk.pdf,replace;

  /* Actual LC: volatility */ 
#delimit;
quietly margins, at(LW=(.1(.1)1) 
hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL )

LC=(0,1) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace);
 mplotoffset, xdimension(LW) plotdimension(at(LC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolLC , replace)   $cs ylabel(-12(2)-2)  title(Leader Change)    ytitle(Volatility in W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) cap() /*note("hello")*/;  
preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolLCs2 , replace) title(Leader Change)    ytitle("Volatility in W, {&sigma}{sup:2}" ) ylabel(0(.01).05)   xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "No Leader Change" 2  "Leader Change")) ;  


 /* Risk LC: volatility */ 
#delimit;
quietly margins, at(LW=(.1(.1)1)
hatrev=($hatrevL ) hatcoup=($hatcoupL ) hatLC=($hatLCL,$hatLCH) 
LC=(0) AnyCoupPT=(0) revyn=0) vsquish predict(equation(lnsigma2)) saving(${store}/file1, replace); 
 mplotoffset, xdimension(LW) plotdimension(at(hatLC) , labels("HE" "sick")   )  byopts(title(""))    name(${n1}VolhatLC , replace)   $cs ylabel(-12(2)-2)  title(Leader Change Risk)    ytitle(Volatility in W)    xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) cap() /*note("hello")*/;
 
preserve; use ${store}/file1, clear; replace _margin=exp(_margin); replace _ci_lb=exp( _ci_lb); replace _ci_ub=exp( _ci_ub); save ${store}/file1, replace; restore;

#delimit;
 combomarginsplot ${store}/file1, $cs name(${n1}VolhatLCs2 , replace) title(Leader Change Risk)    ytitle("Volatility in W, {&sigma}{sup:2}" ) ylabel(0(.01).05)   xtitle(W{sub:t-1})  recast(connected) offset(.04)  legend(col(1) order(1 "Low Risk" 2  "High Risk")) ;  
 
  #delimit;  
 
graph combine ${n1}VolLC ${n1}VolhatLC, col(3) name(${n1}VolEventsRisks, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/${n1}VolEventsRisks.pdf",replace; 
 graph combine ${n1}VolLCs2 ${n1}VolhatLCs2, col(3) name(${n1}VolEventsRiskss2, replace) title("Leader Change and Volatility of Political Institutions"); 
 gr export "${store}/${n1}VolEventsRiskss2.pdf",replace;
  
  


*/

/****************************************************************************/
/************************** Repeated Sampling from the Estimated risks ******/
/****************************************************************************/

 #delimit;
 #delimit; 
 frame change default;
 use "bookproject/December2020/NewWpaper/temp_crap.dta" , clear;
 
 /* rndn.do */
/* recreates a matrix of r by c random normal numbers */
/* Return a matrix R */
capture program drop rndn;
program define rndn , rclass;
*version 6.0;
args  r c ;
tempname R;
local i =1;
local j=1;
mat R = J(`r',`c',0);
while `j'<=`c' {;
while `i'<=`r' {;
mat R[`i',`j'] = invnorm(uniform());
local i=`i'+1;
};
local i=1;
local j=`j'+1;
};
return matrix randnum = R; 
end;
set seed 22072022; 

/****** Define Models *******/
#delimit;
 regen sick=SICK5y,replace; regen D2W= F2.W4 - L.W4,replace ;  regen F2W= F2.W4,replace ;  
    global basicmodel1 "c.LW##c.LW LProt c.LW#c.LProt c.LW#c.LW#c.LProt sick c.LW#c.sick c.LW#c.LW#c.sick 
	logIncomingTenure c.LW#c.logIncomingTenure c.LW#c.LW#c.logIncomingTenure  eAge  Llgdppc Llpop c.growthWB c.LW#c.growthWB  ";
	
	global basicmodel1simple "c.LW##c.LW LProt c.LW#c.LProt  sick c.LW#c.sick 
	logIncomingTenure c.LW#c.logIncomingTenure  eAge  Llgdppc Llpop c.growthWB c.LW#c.growthWB  ";
global modelbasicW "c.LW c.LW#c.LW revyn AnyCoupPT  c.hatLC c.hatrev  c.hatcoup  i.year i.ccode"; 
global sigmaWsmall "c.hatLC LC  c.LW c.LW#c.LW     "; 


global modelbasicW "c.LW c.LW#c.LW revyn AnyCoupPT    c.hatrev  c.hatcoup  i.year i.ccode";  
global modelbasicW "c.LW c.LW#c.LW revyn AnyCoupPT    c.hatrev  c.hatcoup  i.year ";  
 global modelbasicW "c.LW c.LW#c.LW LC revyn AnyCoupPT hatLC   c.hatrev  c.hatcoup   "; 
 global sigmaWsmall "c.hatrev c.hatcoup   c.LW c.LW#c.LW     "; 
global sigmaWsmall "c.hatLC LC  c.LW c.LW#c.LW     "; 
 
#delimit;
/*
/****** First stage model with 2 fixed effects *******/
capture drop yearLC ccodeLC;
reghdfe   LC $basicmodel1simple, absorb(yearLC=year ccodeLC=ccode, save) vce(cluster ccode) resid; 
mat bhatLC = e(b);mat CLC = cholesky(e(V));
global kLC `= colsof(bhatLC)';*/
/****** First stage model with xtreg *******/

xtreg LC $basicmodel1, fe i(ccode); capture drop xb; capture drop xbu;
predict uLC,u;  
mat bhatLC = e(b);mat CLC = cholesky(e(V));
global kLC `= colsof(bhatLC)';
xtreg revyn $basicmodel1, fe i(ccode); capture drop urev;
predict urev,u; 
mat bhatrev = e(b);mat Crev = cholesky(e(V));
global krev `= colsof(bhatrev)';
xtreg AnyCoupPT $basicmodel1, fe i(ccode); capture drop uCoup;
predict uCoup,u; 
mat bhatCoup = e(b);mat CCoup = cholesky(e(V));
global kCoup `= colsof(bhatCoup)';
*/
/*
/****** First stage model with logit *******/
#delimit;
logit LC $basicmodel1  ;  
mat bhatLC = e(b);mat CLC = cholesky(e(V));
global kLC `= colsof(bhatLC)';
logit revyn $basicmodel1  ;
mat bhatrev = e(b);mat Crev = cholesky(e(V));
global krev `= colsof(bhatrev)';
logit AnyCoupPT $basicmodel1  ;
mat bhatCoup = e(b);mat CCoup = cholesky(e(V));
global kCoup `= colsof(bhatCoup)';

regen uLC=0,replace; regen urev=0,replace;regen uCoup=0,replace;
*/
/*
/* first stage as basic regression */reg LC $basicmodel1  ;  
mat bhatLC = e(b);mat CLC = cholesky(e(V));
global kLC `= colsof(bhatLC)';
reg revyn $basicmodel1  ;
mat bhatrev = e(b);mat Crev = cholesky(e(V));
global krev `= colsof(bhatrev)';
reg AnyCoupPT $basicmodel1  ;
mat bhatCoup = e(b);mat CCoup = cholesky(e(V));
global kCoup `= colsof(bhatCoup)';

regen uLC=0,replace; regen urev=0,replace;regen uCoup=0,replace;
*/
/**** Setup Output Storage ****/ 
#delimit;
global temp simBeta;capture frame drop $temp; 

frame create $temp   int(Iteration)   double(betahatLC) double(SEhatLC)
double(betahatrev) double(SEhatrev) double(betahatcoup) double(SEhatcoup) double(sigmahatLC) double(sigmaSEhatLC) ;
/*
frame create $temp int(Iteration) double(betahatrev) double(betahatcoup) double(sigmahatrev) double(sigmahatcoup); 
*/
/******* Iterate though to sample *******/ 
forvalues  iter = 1/100{;
di "Iteration  `iter'" ; 

#delimit; 

/******* Draw random beta and create predicted values ********/ 
quietly{ ; rndn $kLC 1 ; mat define bLC = bhatLC + r(randnum)'*CLC; capture drop hat; 
matrix score hat= bLC ; regen hatLC = hat +uLC,replace;
rndn $krev 1 ; mat define brev = bhatrev + r(randnum)'*Crev;capture  drop hat;
matrix score hat= brev  ; regen hatrev = hat +urev,replace; 
rndn $kCoup 1 ; mat define bCoup = bhatCoup + r(randnum)'*CCoup;capture drop hat;
matrix score hat= bCoup  ; regen hatcoup = hat +uCoup,replace; 
};

qui hetregress D2W $modelbasicW  i.ccode, het($sigmaWsmall );
mat vv =e(V); 

scalar sigmaSEhatLC= sqrt(vv["lnsigma2:hatLC" ,"lnsigma2:hatLC" ]);
scalar SEhatLC= sqrt(vv["D2W:hatLC" ,"D2W:hatLC" ]);
scalar SEhatrev= sqrt(vv["D2W:hatrev" ,"D2W:hatrev" ]);
scalar SEhatcoup= sqrt(vv["D2W:hatcoup" ,"D2W:hatcoup" ]);
scalar betahatLC= _b["D2W:hatLC" ];
scalar sigmahatLC= _b["lnsigma2:hatLC" ];
scalar betahatrev= _b["D2W:hatrev"];
scalar betahatcoup= _b["D2W:hatcoup"];
/*** post sample ****/ 

 frame post $temp (`iter') (betahatLC) (SEhatLC) 
(betahatrev)  (SEhatrev) (betahatcoup)  (SEhatcoup)
 (sigmahatLC)  (sigmaSEhatLC);  
 /*


scalar sigmaSEhatRev= sqrt(vv["lnsigma2:hatrev" ,"lnsigma2:hatrev" ]);

scalar SEhatrev= sqrt(vv["D2W:hatrev" ,"D2W:hatrev" ]);
scalar SEhatcoup= sqrt(vv["D2W:hatcoup" ,"D2W:hatcoup" ]);

scalar betahatrev= _b["D2W:hatrev"];
scalar betahatcoup= _b["D2W:hatcoup"];
scalar sigmahatrev= _b["lnsigma2:hatrev"];
scalar sigmahatcoup= _b["lnsigma2:hatcoup"];
/*** post sample ****/ 

 frame post $temp (`iter') (betahatrev) (betahatcoup) 
(sigmahatrev)  (sigmahatcoup);  */
}; 

frame $temp: sum;

 
 
 #delimit;
frame change $temp; 

/* calculate SE */
sum Iteration;
scalar m=r(max) ;

sum betahatLC ;
scalar meanbetahatLC= r(mean);
scalar s2betahatLC = sum((betahatLC-meanbetahatLC)^2)/(m-1);
scalar seLCb=sqrt((sum(SEhatLC^2)/m)+s2betahatLC*(m+1)/m);
di "BetaHat: LC";
di "beta" meanbetahatLC;
di "se" seLCb;
di "tstat" meanbetahatLC/seLCb;
count if betahatLC/SEhatLC>1.96;
count if betahatLC/SEhatLC<-1.96;





sum betahatrev ;
scalar meanbetahatrev= r(mean);
scalar s2betahatrev = sum((betahatrev-meanbetahatrev)^2)/(m-1);
scalar seRevb=sqrt((sum(SEhatrev^2)/m)+s2betahatrev*(m+1)/m);
di "BetaHat: Rev";
di "beta" meanbetahatrev;
di "se" seRevb;
di "tstat"  betahatrev/seRevb;
count if meanbetahatrev/SEhatrev>=1.96; 

sum betahatcoup ;
scalar meanbetahatcoup= r(mean);
scalar s2betahatcoup = sum((betahatcoup-meanbetahatcoup)^2)/(m-1);
scalar seCoupb=sqrt((sum(SEhatcoup^2)/m)+s2betahatcoup*(m+1)/m);
di "BetaHat: Coup";
di "beta" meanbetahatcoup;
di "se" seCoupb;
di "tstat" meanbetahatcoup/seCoupb;
count if meanbetahatcoup/SEhatcoup<-1.96; 


sum sigmahatLC ;
scalar meansigmahatLC= r(mean);
scalar s2 = sum((sigmahatLC-meansigmahatLC)^2)/(m-1);
scalar seSigmaLCb=sqrt((sum(sigmaSEhatLC^2)/m)+s2*(m+1)/m);
di "SigmaHat: LC";
di "beta" meansigmahatLC;
di "se" seSigmaLCb;
di "tstat" meansigmahatLC/seSigmaLCb;
count if sigmahatLC/sigmaSEhatLC>1.96; 



kdensity betahatrev, name(betahatrev,replace) ; 
kdensity betahatcoup, name(betahatcoup,replace) ; 

capture kdensity sigmahatrev, name(sigmahatrev,replace) ; 
capture kdensity sigmahatcoup, name(sigmahatcoup,replace) ; 

regen Thatrev=betahatrev/SEhatrev,replace; 
regen Thatcoup=betahatcoup/SEhatcoup,replace; 
regen ThatLC=betahatLC/SEhatLC,replace; 
regen TsigmahatLC=sigmahatLC/sigmaSEhatLC,replace; 

kdensity betahatrev, name(betahatrev,replace) ; 
kdensity Thatrev, name(Thatrev,replace); 
kdensity  Thatcoup, name(Thatcoup,replace);
kdensity ThatLC, name(ThatLC,replace);
kdensity TsigmahatLC , name(TsigmahatLC,replace); 
 
frame change default; 
 
 
 
 
 
 
 
 
 
 
 /*global modelbasicWevents "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatrev  c.hatcoup c.rev AnyCoupPT  yr* i.ccode";
global modelbasicWb "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatLC LC c.hatrev revyn c.hatcoup  AnyCoupPT yr* i.ccode";
global modelbasicWc "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatLC LC c.hatrev revyn c.hatcoup  AnyCoupPT yr* i.ccode";
global modelbasicWc_control "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatLC LC c.hatrev revyn c.hatcoup  AnyCoupPT growthWB c.LW#c.growthWB c.LW##c.Llgdppc Llpop yr* i.ccode";
*/
 global title "How the Occurrence of Leader Change, Revolution and Coup and the Risk of these Events Affects the Direction and Volatility of Institutional Change";
global modelfullW3 "c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.hatLC c.LW#c.hatLC  LC c.LW#c.LC c.hatrev  c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global modelbasicW3 "c.LW c.LW#c.LW  c.LW#c.LW#c.LW c.hatLC c.hatrev  c.hatcoup   yr* i.ccode";
global modelbasicWevents3 "c.LW c.LW#c.LW  c.LW#c.LW#c.LW LC c.rev AnyCoupPT  yr* i.ccode";
global modelbasicWboth3 "c.LW c.LW#c.LW  c.LW#c.LW#c.LW LC c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode";


global modelfullW "c.LW c.LW#c.LW   c.hatLC c.LW#c.hatLC  LC c.LW#c.LC c.hatrev  c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop yr* i.ccode";
global modelbasicW "c.LW c.LW#c.LW   c.hatLC c.hatrev  c.hatcoup   yr* i.ccode";
global modelbasicWevents "c.LW c.LW#c.LW   LC c.rev AnyCoupPT  yr* i.ccode";
global modelbasicWboth "c.LW c.LW#c.LW   LC c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode";

global sigmaWfull "c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.hatLC LC c.LW#LC c.hatrev  c.LW#c.hatrev c.hatcoup c.LW#c.hatcoup growthWB c.LW#c.growthWB Llgdppc Llpop ";  
global sigmaWsmall3 "c.hatLC LC  c.LW c.LW#c.LW  c.LW#c.LW#c.LW   ";
global sigmaWsmall "c.hatLC LC  c.LW c.LW#c.LW     ";  
 global sigmaWrevcoup "c.hatLC LC  c.LW#c.hatLC c.LW#c.LC c.LW c.LW#c.LW  c.LW#c.LW#c.LW   "; 
  #delimit;
  
/** Program to calc stat for tables **/ 
capture program drop addstuff; program define addstuff; estadd scalar fe feNation;  estadd scalar AIC = 2 *e(k)-2*e(ll);capture drop hatfull; predict hatfull if sam==1, xb; regen resfull2=(D2W-hatfull)^2 if sam==1,replace; sum resfull2 if sam==1; scalar resfullSum = r(sum);
estadd scalar r2non= (resNonSum-resfullSum)/resNonSum;end;   
  
/**** Use xtreg predictions ****/ 
regen hatrev = hatrevW,replace; regen hatcoup=hatcoupW,replace ; regen hatLC=hatLCW,replace; 
  #delimit; /*** run a regression to find common sample **/ 
hetregress D2W $modelbasicWboth , het($sigmaWsmall ); regen sam=e(sample),replace;
/* get sum of squared error to calc R2 later */  
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);

hetregress D2W $modelbasicWevents, het($sigmaWsmall ); eststo m0; 
addstuff;

hetregress D2W $modelbasicW, het($sigmaWsmall ); eststo m1;addstuff;
hetregress D2W $modelbasicWboth, het($sigmaWsmall ); eststo m2;addstuff;
hetregress D2W c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==0& F.LC==0, het(c.hatLC    c.LW c.LW#c.LW  c.LW#c.LW#c.LW    ); regen sam=e(sample),replace; 
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);
hetregress D2W c.LW c.LW#c.LW    c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==0& F.LC==0, het(c.hatLC    c.LW c.LW#c.LW      );
eststo m3; addstuff; 

#delimit;
hetregress D2W c.LW c.LW#c.LW  c.LW#c.LW#c.LW  c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==1| F.LC==1, het(c.hatLC   c.LW c.LW#c.LW     ); regen sam=e(sample),replace; 
quietly tab ccode if sam==1; scalar feNation =r(r); 
regress D2W if sam==1;  capture drop hatNon; predict hatNon if sam==1, xb;
regen resNon2=(D2W-hatNon)^2 if sam==1, replace;  sum resNon2 if sam==1; scalar resNonSum = r(sum);
hetregress D2W c.LW c.LW#c.LW    c.rev AnyCoupPT c.hatLC c.hatrev  c.hatcoup yr* i.ccode if LC==1| F.LC==1, het(c.hatLC   c.LW c.LW#c.LW      );
eststo m4;addstuff; 
global DWtitle "How Leader Change, Revolution, Coup and the Threat of these Events Affect Institutional Change and Institutional Volatility"; 
global mtitle " "Events" "Risk" "Both" "No LC" "LC" "; 
    #delimit;
 esttab m0 m1 m2   using "${store}/SimpleD2W.tex",replace ar2 r2 se 
   title("$DWtitle (Risks estimated from analyses in table \ref{tab:threatWxtreg})  \label{tab:SimpleD2W}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels( "Events" "Risk" "Both" "No LC" "LC" ) substitute(\~ $)   ;  

 esttab m0 m1 m2 m3 m4  using "${store}/SimpleD2WExtra.tex",replace ar2 r2 se 
   title("$DWtitle (Risks estimated from analyses in table \ref{tab:threatWxtreg})  \label{tab:SimpleD2WExtra}" ) 
   stats( N fe r2non ll AIC  ,
	labels("Observations" "Fixed Effects" "R2" "loglike." "AIC" )fmt(0  0 %10.4f %11.4f %11.4f %8.4f %8.2f %8.2f %8.2f %8.2f)) 
  star(+ 0.10 * 0.05 ** 0.01 *** 0.001) varlabel($labvar)
 drop( _cons  yr yr2 yr3 *.ccode  ) mlabels($mtitle ) substitute(\~ $)   ;  
    